package com.leeyu.rabbitmq.routing;

import com.leeyu.rabbitmq.util.RabbitMQConnectionUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.junit.Test;

import java.nio.charset.StandardCharsets;

public class Publisher {

    private static final String EXCHANGE_NAME = "routing";
    private static final String QUEUE_NAME1 = "routing-one";
    private static final String QUEUE_NAME2 = "routing-two";

    @Test
    public void publish() throws Exception {
        // 获取连接
        Connection connection = RabbitMQConnectionUtil.getConnection();

        // 构建channel
        Channel channel = connection.createChannel();

        // 构建交换机
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

        // 构建队列
        channel.queueDeclare(QUEUE_NAME1, false, false, false, null);
        channel.queueDeclare(QUEUE_NAME2, false, false, false, null);

        // 绑定交换机和队列
        channel.queueBind(QUEUE_NAME1, EXCHANGE_NAME, "ORANGE");
        channel.queueBind(QUEUE_NAME2, EXCHANGE_NAME, "BLACK");
        channel.queueBind(QUEUE_NAME2, EXCHANGE_NAME, "GREEN");

        // 发送消息到交换机
        channel.basicPublish(EXCHANGE_NAME, "ORANGE", null, "Routing模式：大橙子！".getBytes(StandardCharsets.UTF_8));
        channel.basicPublish(EXCHANGE_NAME, "BLACK", null, "Routing模式：黑布林大李子！".getBytes(StandardCharsets.UTF_8));
        channel.basicPublish(EXCHANGE_NAME, "GREEN", null, "Routing模式：大青菜叶子！".getBytes(StandardCharsets.UTF_8));
        System.out.println("消息发送成功！");
    }
}
